/**
 * Copyright(C) 2011-2012 cheng.chun TBTOSOFT
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 */
package com.tbtosoft.util4j;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

/**
 * @author chengchun
 *
 */
public final class HexString {
    public static String byteToHexString(byte[] data){
        StringBuffer buffer = new StringBuffer();
        for(int index = 0; index < data.length; index++){
            buffer.append(String.format("%02X", data[index]));
        }        
        return buffer.toString();
    }
    public static byte[] hexStringToByte(String hexString){
        byte[] result = new byte[hexString.length()/2];
        for(int index = 0; index < result.length; index++){
            String str = hexString.substring(index*2, (index+1)*2);
            result[index] = Byte.parseByte(str, 16);
        }
        return result;
    }
    public static String getString(ByteBuffer buffer, int length){
    	byte[] tmp = new byte[length];
    	buffer.get(tmp, 0, length);
    	int pos = 0;
    	for (; pos < tmp.length && tmp[pos] != 0x00; pos++);
    	return new String(tmp, 0, pos);
    }
    public static String getString(ByteBuffer buffer, int length, Charset charset){
    	byte[] tmp = new byte[length];
    	buffer.get(tmp, 0, length);
    	int pos = 0;
    	for (; pos < tmp.length && tmp[pos] != 0x00; pos++);
    	return new String(tmp, 0, pos, charset);
    }
    public static byte[] getBytes(String value, int length){
    	byte[] bytes = new byte[length];
    	byte[] tmp = value.getBytes();
    	int size = tmp.length > length ? length : tmp.length;
    	System.arraycopy(tmp, 0, bytes, 0, size);
    	return bytes;
    }
}
